package com.ihealthway.all.interfaces.dwihealth.service;

import com.ihealthway.all.interfaces.dwihealth.XMLBuilder;
import com.ihealthway.all.interfaces.dwihealth.vo.*;
import org.nutz.dao.impl.NutDao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
@IocBean
public class DWCustomerService {

    private static final Log logger = Logs.get();

    @Inject
    private NutDao dao;

    private String respCnt = XMLBuilder.simpleResp("1", "Success", null);

    public String syncAdd(List<DWCustomer> customers) {
        return insertOrUpdate(customers);
    }

    public String syncUpdate(List<DWCustomer> customers) {
        return insertOrUpdate(customers);
    }

    private String insertOrUpdate(List<DWCustomer> customers) {
        String respContent = this.respCnt;

        List<ErrorInfoElement> errors = new ArrayList<>();
        List<DWCustomer> data = new ArrayList<>();
        List<DWCustSerItem> subData = new ArrayList<>();

        for (DWCustomer cust : customers) {
            ErrorInfoElement error = cust.valid();
            if (error!=null) {
                errors.add(error);
                continue;
            }

            data.add(cust);

            List<DWCustSerItem> items = cust.getCustSerItems();
            if (items!=null && !items.isEmpty()) {
                for (DWCustSerItem item : items) {
                    ErrorInfoElement subError = item.valid(cust.getCustNo());
                    if (subError!=null) {
                        errors.add(subError);
                        continue;
                    }

                    subData.add(item);
                }
            }
        }



        if (!errors.isEmpty()) {
            respContent = XMLBuilder.simpleResp("0", "Failure", errors);
        } else {
            try {
                if (!data.isEmpty()) {
                    this.dao.insertOrUpdate(data);
                }
                if (!subData.isEmpty()) {
                    this.dao.insertOrUpdate(subData);
                }
            } catch (Exception e) {
                logger.error("Insert/Update DW customer and customer service plan data fail!!!", e);
            }
        }

        return respContent;
    }

}
